<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { getSearchWallApi } from '@/api/index'
import { useWallStore } from '@/store'
import { safeAreaInsets } from '@/utils/systemInfo'

definePage({
  style: {
    navigationBarTitleText: '搜索',
  },
})
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
})
let { historySearch, classList: listData, classListTotal } = storeToRefs(useWallStore())

// 热门搜索词
const recommendList = ref(['美女', '帅哥', '宠物', '卡通'])

// 没有更多
const noData = ref(false)
// 没有搜索结果
const noSearch = ref(false)

// 搜索结果列表
let classList = ref([])

// 点击搜索
async function onSearch() {
  uni.showLoading({
    title: '加载中...',
  })
  classList.value = []
  noData.value = false
  noSearch.value = false
  historySearch.value = [...new Set([queryParams.value.keyword, ...historySearch.value])].slice(0, 10)
  searchWall()
}

// 点击清除按钮
function onClear() {
  initParams()
}

// 点击标签进行搜索
function clickTab(value) {
  uni.showLoading({
    title: '加载中...',
  })
  initParams()
  queryParams.value.keyword = value
  historySearch.value = [...new Set([queryParams.value.keyword, ...historySearch.value])]
  searchWall()
}

// 点击清空搜索记录
function removeHistory() {
  uni.showModal({
    title: '是否清空历史搜索？',
    success: (res) => {
      if (res.confirm) {
        historySearch.value = []
        console.log('确认删除')
      }
    },
  })
}
async function searchWall() {
  try {
    let res = await getSearchWallApi(queryParams.value)
    uni.hideLoading()
    classList.value = [...classList.value, ...res]

    if (queryParams.value.pageSize > res.length) {
      noData.value = true
    }
    if (res.length === 0 && classList.value.length === 0) {
      noSearch.value = true
    }
  }
  catch (e) {
    uni.hideLoading()
    console.log(e)
  }
}
function initParams() {
  classList.value = []
  noData.value = false
  noSearch.value = false
  queryParams.value = {
    pageNum: 1,
    pageSize: 12,
    keyword: '',
  }
}
function goPreview(item) {
  listData.value = classList.value
  uni.navigateTo({
    url: `/pages/preview/preview?id=${item._id}`,
  })
}

// 触底加载更多
onReachBottom(() => {
  if (noData.value)
    return
  queryParams.value.pageNum++
  searchWall()
})

// 关闭有页面
onUnload(() => {
  listData.value = []
})
onLoad(() => {
  console.log(safeAreaInsets, 'safeAreaInsets')
})
</script>

<template>
  <view class="searchLayout">
    <view class="search">
      <uni-search-bar
        v-model="queryParams.keyword" focus placeholder="搜索" @confirm="onSearch" @cancel="onClear"
        @clear="onClear"
      />
    </view>

    <view v-if="!classList.length || noSearch">
      <view v-if="historySearch.length" class="history">
        <view class="topTitle">
          <view class="text">
            最近搜索
          </view>
          <view class="icon" @click="removeHistory">
            <uni-icons type="trash" size="25" />
          </view>
        </view>
        <view class="tabs">
          <view v-for="tab in historySearch" :key="tab" class="tab" @click="clickTab(tab)">
            {{ tab }}
          </view>
        </view>
      </view>

      <view class="recommend">
        <view class="topTitle">
          <view class="text">
            热门搜索
          </view>
        </view>
        <view class="tabs">
          <view v-for="tab in recommendList" :key="tab" class="tab" @click="clickTab(tab)">
            {{ tab }}
          </view>
        </view>
      </view>
    </view>

    <view v-if="noSearch" class="noSearch">
      <uv-empty mode="search" icon="/static/images/empty.png" />
    </view>

    <view v-else>
      <view class="list">
        <view v-for="(item, index) in classList" :key="item._id + index" class="item" @click="goPreview(item)">
          <image :src="item.smallPicurl" mode="aspectFill" />
        </view>
      </view>
      <view v-if="noData || classList.length" :style="{ paddingBottom: `${safeAreaInsets.bottom}px` }">
        <uni-load-more :status="noData ? 'noMore' : 'loading'" />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.searchLayout {
  .search {
    padding: 0 10rpx;
  }

  .topTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 32rpx;
    color: #999;
  }

  .history {
    padding: 30rpx;
  }

  .recommend {
    padding: 30rpx;
  }

  .tabs {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding-top: 20rpx;

    .tab {
      background: #f4f4f4;
      font-size: 28rpx;
      color: #333;
      padding: 10rpx 28rpx;
      border-radius: 50rpx;
      margin-right: 20rpx;
      margin-top: 20rpx;
    }
  }

  .list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 5rpx;
    padding: 20rpx 5rpx;

    .item {
      height: 440rpx;

      image {
        width: 100%;
        height: 100%;
        display: block;
      }
    }
  }
}
</style>
